package com.zoe.app.intercept;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zoe.app.anno.AutoIdempotent;
import com.zoe.app.config.TokenService;
import com.zoe.app.exception.IdempotentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author Zoe.Zhang
 * @date 2021/10/24
 * @description
 */
@Component
public class IdempotentIntercept implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod idempotentMethod = (HandlerMethod) handler;
        Method method = idempotentMethod.getMethod();

        AutoIdempotent annotation = AnnotationUtil.getAnnotation(method, AutoIdempotent.class);
        if (ObjectUtil.isNotNull(annotation)) {
            try {
                return tokenService.verifyToken(request);
            } catch (IdempotentException e) {
                throw e;
            }
        }

        return true;
    }
}
